package com.company.project.common.spring;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;


public class SpringUtils {

    public static ApplicationContext applicationContext;

    public static  <T> T getBean(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static boolean isDev() {
        return "dev".equals(applicationContext.getEnvironment().getActiveProfiles()[0]);
    }

    /**
     * 获取yml里边的值s
     * @param key
     * @return
     */
    public static String getConfigValue(String key) {
        Environment environment = applicationContext.getEnvironment();
        return environment.getProperty(key);
    }


    /**
     * 主动向Spring容器中注册bean
     * @param clazz  注册的class
     * @param obj  对象
     * @return 返回注册到容器中的bean对象
     */
    public static synchronized void registerSingleton(Class<?> clazz, Object obj) {
        if (obj == null) {
            return;
        }
        Object bean = getBean(clazz);
        if (bean != null) {
            throw new RuntimeException("对象已经存在");
        }
        String simpleName = clazz.getSimpleName();
        if (simpleName.length() == 1) {
            simpleName = simpleName.toLowerCase();
        }else {
            simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
        }

        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
        beanFactory.registerSingleton(simpleName, obj);
    }
    /**
     * 删除bean
     * @param clazz  clazz
     * @return 返回注册到容器中的bean对象
     */
    public static synchronized void destroySingleton(Class<?> clazz) {
        Object bean = getBean(clazz);
        if (bean != null) {
            String simpleName = clazz.getSimpleName();
            if (simpleName.length() == 1) {
                simpleName = simpleName.toLowerCase();
            }else {
                simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
            }
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
            beanFactory.destroySingleton(simpleName);
        }
    }


}
